local cjson = require "cjson"

local M = {}
local prefixLen = 2

function M.json_pack_with_prefix(msg, prefix)
    local body = cjson.encode(msg) -- 协议体字节流
    local bodylen = string.len(body) -- 协议体长度
    local format = string.format("> i%d c%d", prefixLen, bodylen)
    local buff = string.pack(format, bodylen, body)
    return buff
end

function M.json_unpack_with_prefix(buff)
    local len = string.len(buff)
    local format = string.format("> i%d c%d", prefixLen, len - 2)
    local bodylen, body = string.unpack(format, buff)

    local isok, msg = pcall(cjson.decode, body)
    if not isok or not msg then
        print("json_unpack_with_prefix error")
        return
    end

    return msg
end

function M.json_pack_no_prefix(msg)
    local body = cjson.encode(msg) -- 协议体字节流
    local bodylen = string.len(body) -- 协议体长度
    local format = string.format("> c%d", bodylen)
    local buff = string.pack(format, body)
    return buff
end

function M.json_unpack_no_prefix(buff)
    local len = string.len(buff)
    local format = string.format("> c%d", len)
    local body = string.unpack(format, buff)

    local isok, msg = pcall(cjson.decode, body)
    if not isok or not msg then
        print("json_unpack_no_prefix error")
        return
    end

    return msg
end

return M
